package com.yxy.controller.app;

import com.yxy.common.Const;
import com.yxy.common.ServerResponse;
import com.yxy.common.enums.SportTypeEnum;
import com.yxy.controller.service.SportController;
import com.yxy.dto.SportModel;
import com.yxy.entity.Sport;
import com.yxy.jpush.Jpush;
import com.yxy.service.SportService;
import com.yxy.util.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Controller
@RequestMapping("/app/sports")
public class AppSportController {


    public Logger logger = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private SportService sportService;


    //列表
    @RequestMapping(value = "list", method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse<List<SportModel>> list(int pageNum, int pageSize,Integer sportTypeId,Integer sortCondition) throws Exception{
        List<SportModel> sportModelList= new ArrayList<SportModel>();
        List<Sport> sportList = sportService.findPage(pageNum,pageSize,sportTypeId,sortCondition);
        if(sportList!=null && sportList.size()>0){
            for (Sport sport:sportList) {
                SportModel sportModel = new SportController().entityToModel(sport);
                sportModelList.add(sportModel);
            }
        }
        return ServerResponse.createBySuccess("查询成功",sportModelList);
    }

    //添加
    @RequestMapping(value = "create", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<SportModel> cerate(@RequestBody Sport sport, HttpServletRequest request){
//        Sport sport = new SportController().modelToEntity(sportModel);
        if(sport!=null){
            setTemplateDateAndUser(sport,request);
            sport.setSportStartDatetime(DateUtils.beforeEigntHours(sport.getSportStartDatetime()));
            sport.setSportEndDatetime(DateUtils.beforeEigntHours(sport.getSportEndDatetime()));//时间调整8小时
            sport.setSportEndWeek(DateUtils.getWeekByDate(sport.getSportEndDatetime()));
            sport.setSportStartWeek(DateUtils.getWeekByDate(sport.getSportStartDatetime()));
            if(sport.getPubSportTypeId()!=null){
                String sportTypeId= String.valueOf(sport.getPubSportTypeId());
                sport.setPubSportTypeName(SportTypeEnum.getValues(sportTypeId).getSportTypeName());
                sport.setPubSportImg(SportTypeEnum.getValues(sportTypeId).getSportTypeBgImg());//活动信息图片
                sport.setSportTypeImg(SportTypeEnum.getValues(sportTypeId).getSportTypeImg());//活动类型图标


            }
            if(sportService.create(sport)){
                //从前端页面传个参数过来判断是否推送
//                if((infoMap.get("is_push").toString()).trim().equals("1")){
                //设置推送参数
                //这里同学们就可以自定义推送参数了
                Map<String, String> parm =new HashMap<String, String>();
                //这是我的文章id
//                    parm.put("id",(""+id).trim());
                //文章标题
                parm.put("Atitle",sport.getPubSportTitle());
                //设置提示信息,内容是文章标题
                parm.put("msg","你有活动提醒你参加");
                //然后调用安卓的
                new Jpush().jpushAndroid(parm);
//                }
                return ServerResponse.createBySuccessMessage("运动发布成功");
            }
        }
        return ServerResponse.createByErrorMessage("活动发布失败,请重试");
    }

    //删除
    @RequestMapping("delete")
    @ResponseBody
    public ServerResponse delete(Integer id,HttpServletRequest request) throws Exception{
        Sport sport = new Sport();
        sport.setId(id);
        setTemplateDateAndUser(sport,request);
        if(sportService.delete(sport)){
            return ServerResponse.createBySuccessMessage("活动删除成功");
        }
        return ServerResponse.createByErrorMessage("操作失败，请重试！");
    }

    //参加活动
    @RequestMapping(value = "join", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<SportModel> join(@RequestBody SportModel sportModel,HttpServletRequest request){
        Integer userId = Integer.parseInt(sportModel.getJoinUserId());
        Sport sport = new SportController().modelToEntity(sportModel);

        setTemplateDateAndUser(sport,request);
        Integer resultCode = sportService.joinSport(sport,userId);

        if(resultCode ==Const.SportFlag.SPORT_FLAG_PERSON_FULL){
            return ServerResponse.createByErrorCodeMessage(Const.USERS_IS_FULL,"人数已满");
        }
        if(resultCode ==Const.SportFlag.SPORT_FLAG_CABCEL_JOIN){
            return ServerResponse.createByErrorCodeMessage(Const.ALREADY_JOIN_SPORT,"您已取消活动动");
        }
        return ServerResponse.createBySuccessMessage("您已成功加入该活动，请准时参加!");
    }

    @RequestMapping(value = "select", method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse<SportModel> select(Integer id,Integer userId) throws Exception{
        Sport sport = sportService.findOne(id,userId);
        if (sport!=null){
            SportModel sportModel = new SportController().entityToModel(sport);
            return ServerResponse.createBySuccess("成功获取信息",sportModel);
        }
        return ServerResponse.createByErrorMessage("活动不存在");
    }

    @RequestMapping(value = "cancelJoinSport", method = RequestMethod.DELETE)
    @ResponseBody
    public ServerResponse<SportModel> CancelJoinSport(Integer sportId,Integer userId){
        Sport sport = new Sport();
        sport.setId(sportId);
        if(sportService.CancleJoinSport(sport,userId)){
            return ServerResponse.createBySuccessMessage("您已取消参加该活动");
        }
        return ServerResponse.createByErrorMessage("取消操作失败,请重试");
    }
    @RequestMapping(value = "cancelSport", method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse CancelSport(Integer sportId){
        if(sportService.CancelSport(sportId)){
            return ServerResponse.createBySuccessMessage("活动已成功取消");
        }
        return ServerResponse.createByErrorMessage("活动取消失败");
    }

    @RequestMapping(value = "selectListByUserId", method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse selectListByUserId(Integer userId)throws Exception{
        List<Sport> sportList = sportService.selectListByUserId(userId);
       if(sportList!=null && sportList.size()>0){
           List<SportModel> sportModelList =new ArrayList<>();
           for (Sport sport:sportList) {
               SportModel sportModel =new SportController().entityToModel(sport);
               sportModelList.add(sportModel);
           }
           return ServerResponse.createBySuccess("成功获取列表",sportModelList);
       }
       return ServerResponse.createByErrorMessage("无列表信息");
    }

    @RequestMapping(value = "selectIJoinSports", method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse selectIJoinSports(Integer userId)throws Exception{
        List<Sport> sports = sportService.selectIJoinSports(userId);
        if(sports!=null && sports.size()>0){
            List<SportModel> sportModelList =new ArrayList<>();
            for (Sport sport:sports) {
                SportModel sportModel =new SportController().entityToModel(sport);
                sportModelList.add(sportModel);
            }
            return ServerResponse.createBySuccess("成功获取列表",sportModelList);
        }
        return ServerResponse.createByErrorMessage("无列表信息");
    }

    //猜你喜欢接口
    @RequestMapping(value = "loveSports", method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse loveSports(Integer userId) throws Exception{
        List<Sport> sportList = sportService.selectLoveSports(userId);
        if(sportList!=null && sportList.size()>0){
            List<SportModel> sportModelList = new ArrayList<SportModel>();
            for (Sport sport:sportList) {
                SportModel sportModel = new SportController().entityToModel(sport);
                sportModelList.add(sportModel);
            }
            return ServerResponse.createBySuccess("查询成功",sportModelList);
        }
        return ServerResponse.createByErrorMessage("暂无信息");
    }

    @RequestMapping(value = "tuisong", method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse selectIJoinSports(){
        new Jpush().tuisong();
        return ServerResponse.createBySuccessMessage("请求成功");
    }

    /**
     * 统一设置 Date
     *
     * @param entity
     */
    public void setTemplateDateAndUser(Sport entity, HttpServletRequest request) {

        if (entity == null) {
            logger.error("ERR:Date set error.");
            return;
        }
        if (entity.getId() == null && entity.getCreateTime() == null) {
            //如果id为空， 就是新建
            entity.setCreateTime(new Date());
        } else {

            if (entity.getUpdateTime() == null) {
                entity.setUpdateTime(new Date());
            }
        }
    }



}
